<template>

  <div class="app-container">

    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="提交审核"/>
    </el-steps>

    <el-form label-width="120px">

      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 所属分类 TODO -->
      <el-form-item label="课程分类">
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="一级分类" @change="getTwoSubject">
          <el-option
            v-for="subject in subjectOneList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>

        <el-select
          v-model="courseInfo.subjectId"
          placeholder="二级分类">
          <el-option
            v-for="subject2 in subjectTwoList"
            :key="subject2.id"
            :label="subject2.title"
            :value="subject2.id"/>
        </el-select>
      </el-form-item>


      <!-- 课程讲师 -->
      <!--用下拉列表的形式展示-->
      <el-form-item label="课程讲师">
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!-- 课程简介 TODO -->

      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">

        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/edu/oss/fileoss/upload'"
          class="avatar-uploader">
          <img :src="courseInfo.cover">
        </el-upload>

      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/>
        元
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import course from "@/api/edu/course.js";
import subject from "@/api/edu/subject.js";
import Tinymce from '@/components/Tinymce'

export default {
  components: {Tinymce},
  data() {
    return {
      saveBtnDisabled: false,
      //建议所有属性都要加上，否则可能后面会有问题
      courseInfo: {
        //为了删除之后，能回显这个属性需要加上
        title: '',
        subjectId: '',
        cover: '/static/01.jpg',
        price: '',
        description: '',
        lessonNum: '',
        teacherId: '',
        subjectParentId: ''
      },
      teacherList: [],
      subjectOneList: [],
      subjectTwoList: [],
      BASE_API: process.env.BASE_API //api接口地址
    }
  },
  watch: {
    $route(to, from) {
      this.init()
    }
  },
  created() {
    //初始化的时候获取教师列表和学科分类列表
    if (this.$route.params && this.$route.params.id) {
      this.courseId = this.$route.params.id
      this.getInfo();
    } else {
      //先清空所有信息
      this.courseInfo = {},
        this.teacherList = [],
        this.subjectOneList = [],
        this.subjectTwoList = [],
        //如果没有参数就显示所有参数
        this.courseInfo.cover = '/static/01.jpg',
        this.getOneSubjectList();
    }
    //讲师最终都要显示
    this.getTeacherList();
  },
  methods: {
    /**
     * 再次跳转时候的操作
     */
    init() {
      //初始化的时候获取教师列表和学科分类列表
      if (this.$route.params && this.$route.params.id) {
        this.courseId = this.$route.params.id
        this.getInfo();
      } else {
        //先清空所有信息
        this.courseInfo = {},
          this.teacherList = [],
          this.subjectOneList = [],
          this.subjectTwoList = [],
          //如果没有参数就显示所有参数
          this.courseInfo.cover = '/static/01.jpg',
          this.courseInfo.description = '',
          this.getOneSubjectList();
      }
      //讲师最终都要显示
      this.getTeacherList();
    },
    /**
     * 获取课程信息
     */
    getInfo: function () {
      course.getCourseInfo(this.courseId).then(result => {
        console.log(result.data.courseInfo)
        this.courseInfo = result.data.courseInfo;
        //获取所有分类
        subject.getSubject().then(response => {
          this.subjectOneList = response.data.list;
          for (let i = 1; i < this.subjectOneList.length; i++) {
            //获取每一个一级菜单
            let oneSubject = this.subjectOneList[i];
            if (oneSubject.id === this.courseInfo.subjectParentId) {
              //得到匹配的一级菜单,根据id进行比较
              //获取该一级菜单中的所有二级菜单
              this.subjectTwoList = oneSubject.children;
            }
          }
        })
      })
    },
    saveCourseInfo() {
      course.addCourse(this.courseInfo)
        .then(result => {
          //提示成功信息
          this.$message({
            type: 'success',
            message: '课程添加成功!'
          });
          //路由跳转到下一个界面
          this.$router.push({path: '/edu/course/chapter/' + result.data.courseId})
        })
    },
    /**
     * 更新课程数据
     * @param courseInfo
     */
    updateCourseInfo(courseInfo) {
      course.updateCourseInfo(courseInfo).then(result => {
        //提示成功信息
        this.$message({
          type: 'success',
          message: '课程修改成功!'
        });
        //路由跳转到下一个界面
        this.$router.push({path: '/edu/course/chapter/' + this.courseId})
      })
    },
    /**
     * 路由跳转到下一个页面，后面的参数为新增的课程id，暂时设置为1
     */
    next() {
      if (this.$route.params && this.$route.params.id) {
        this.updateCourseInfo(this.courseInfo)
      } else {
        //如果没有参数就保存数据
        this.saveCourseInfo();
      }

    },
    getTeacherList() {
      course.getTeacherList().then(result => {
        this.teacherList = result.data.items;
      })
    },
    /**
     * 获取所有一级分类
     */
    getOneSubjectList() {
      subject.getSubject().then(result => {
        //获得所有的里列表
        this.subjectOneList = result.data.list;
      })
    },
    /**
     * 根据parent_subject_id获取二级分类
     * @param value 参数是会自动传入的绑定了@change事件之后，会自动value的值（框架封装了）
     */
    getTwoSubject(value) {
      for (let i = 0; i < this.subjectOneList.length; i++) {
        if (this.subjectOneList[i].id === value) {
          this.subjectTwoList = this.subjectOneList[i].children;
          //把之前的二级分类清空
          this.courseInfo.subjectId = '';
        }
      }
    },
    /**
     * 上传文件成功之后
     * @param res 返回的数据
     * @param file 上传的文件
     */
    handleAvatarSuccess(res, file) {
      //返回上传的地址
      this.courseInfo.cover = res.data.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isJPG && isLt10M
    }

  }
}
</script>
<!--scoped 只在本页面js生效-->
<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>
